//
//  PatronSelectionViewController.m
//  CS Inventory Manager
//
//  Created by Ian Smith on 3/24/13.
//  Copyright (c) 2013 Transylvania University. All rights reserved.
//

#import "PatronSelectionViewController.h"
#import "DateSelectionViewController.h"
#import "SuccessScreenViewController.h"
#import "AppDelegate.h"
#import "Patron.h"

@interface PatronSelectionViewController () {
    NSMutableArray *currentSelection;
}

@end

@implementation PatronSelectionViewController
@synthesize selectedItem, checkoutPatrons, currentSelection, navBar, cameFromDVC;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)nextButton:(id)sender
{
    if ((self.patronType.selectedSegmentIndex == 0) && (currentSelection.count > 0)) {
        [self performSegueWithIdentifier:@"DateSelection" sender:currentSelection];
    } if (self.selectedFaculty) {
        //Can jump to end b/c faculty is claiming item
        [self performSegueWithIdentifier:@"Success" sender:self.selectedFaculty];
    }
}

//Here we decide what prep needs to be done before the next screen
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    //If the Patron selected is a student, we need to go to the due date screen next
    if ([segue.identifier isEqualToString:@"DateSelection"]) {
        DateSelectionViewController *nextController = segue.destinationViewController;
        nextController.selectedItem = selectedItem;
        nextController.selectedPatron = sender;
        nextController.cameFromDVC = cameFromDVC;
    }
    //If the patron selected is a faculty member, we will be jumping straight to the success screen
    else {
        SuccessScreenViewController *nextController = segue.destinationViewController;
        nextController.selectedItem = selectedItem;
        nextController.selectedFaculty = sender;
        nextController.cameFromDVC = cameFromDVC;
    }
   
}

-(void)backButton:(id)sender
{
    [self dismissViewControllerAnimated:YES completion:NULL];
}

//This is the function that switches between a list of students and a list of faculty based on the Segemented control selection
-(void)typeSelection:(id)sender
{
    //This code is for when "Student" is selected
    if (self.patronType.selectedSegmentIndex == 0) {
        checkoutPatrons = [[NSMutableArray alloc]init];
        AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        //Iterate through the list of Patrons and pull out only students
        for (int i = 0; i < appDelegate.patrons.count; i++) {       
            Patron *object = appDelegate.patrons[i];
            if ([object.patronType isEqualToString:@"Student"]) {
                [checkoutPatrons addObject:object];
            }
        }
    }
    //This code is for when "Faculty" is selected
    else {
        checkoutPatrons = [[NSMutableArray alloc]init];
        AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        //Iterate through the list of Patrons and pull out only faculty
        for (int i = 0; i < appDelegate.patrons.count; i++) {
            Patron *object = appDelegate.patrons[i];
            if ([object.patronType isEqualToString:@"Faculty"]) {
                [checkoutPatrons addObject:object];
            }
        }
    }
    //Make sure all selections and checkmarks are reset if the user switches between patron types
    self.currentSelection = nil;
    self.selectedFaculty = nil;
    currentSelection = [[NSMutableArray alloc] init];
    [self.patronsTableView reloadData];
    [self clearTable];
}

//Wipes the table of all selections and checkmarks
-(void)clearTable {
    for (int i = 0; i < self.checkoutPatrons.count; i++) {
        //clear table of checkmarks
        NSIndexPath *path = [NSIndexPath indexPathForRow:i inSection:0];
        UITableViewCell *cell = [self.patronsTableView cellForRowAtIndexPath:path];
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"Check Out Wizard";
    //Setup the table view to list all of the students (this is the default position for the segmented control)
    checkoutPatrons = [[NSMutableArray alloc]init];
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    for (int i = 0; i < appDelegate.patrons.count; i++) {
        Patron *object = appDelegate.patrons[i];
        if ([object.patronType isEqualToString:@"Student"]) {
            [checkoutPatrons addObject:object];
        }
    }
    self.currentSelection = [[NSMutableArray alloc] init];
    self.view.backgroundColor = [UIColor grayColor];
    self.navBar.topItem.title = @"Check Out Wizard";
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return checkoutPatrons.count;
}

//Cells should display the Patrons name in the form: Lname, Fname
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    
    // Configure the cell...
    Patron *patron = checkoutPatrons[indexPath.row];
    NSMutableString *name = [[NSMutableString alloc] initWithString:patron.lastName];
    [name appendString:@", "];
    [name appendString:patron.firstName];
    cell.textLabel.text = name;
    
    
    return cell;
}

-(void)printCurrent {
    for (int i = 0; i < currentSelection.count; i++) {
        Patron *temp = currentSelection[i];
        NSLog(@"%@", temp.lastName);
    }
}

#pragma mark - Table view delegate
//This controls what happens when a cell is tapped
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //If we are looking at a list of students, we need to handle multiple selection using checkmarks
    if (self.patronType.selectedSegmentIndex == 0) {
        UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
        //If the student is not yet selected, put a checkmark by their name and add them to the array
        if ([selectedCell accessoryType] == UITableViewCellAccessoryNone) {
            [selectedCell setAccessoryType:UITableViewCellAccessoryCheckmark];
            [currentSelection addObject:checkoutPatrons[indexPath.row]];
        }
        //If the student is already selected, uncheck them and remove them from the array
        else {
            [selectedCell setAccessoryType:UITableViewCellAccessoryNone];
            [currentSelection removeObject:checkoutPatrons[indexPath.row]];
        }
        [tableView deselectRowAtIndexPath:indexPath animated:NO];
        [self printCurrent];
    }
    //If we are looking at a list of faculty members, simply update the selection
    else {
        self.selectedFaculty = checkoutPatrons[indexPath.row];
    }
   
}

@end
